package demo.controller;

import demo.common.QueryData;
import demo.common.ResultJson;
import demo.model.College;
import demo.repository.CollegeRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.validation.Valid;
import java.util.List;

/**
 * 学院（College）数据CURD操作控制器
 */
@RestController
@RequestMapping("/college")
public class CollegeController {
    /**
     * 数据库CURD仓库
     */
    private final CollegeRepository repository;

    /**
     * 构造方法，spring boot会自动处理依赖注入
     * @param repository 数据库CURD仓库
     */
    public CollegeController(CollegeRepository repository) {
        this.repository = repository;
    }

    /**
     * 执行查询
     * @param queryData 查询对象
     * @return 查询结果，学院列表在 res.data.items 中，记录数在 res.data.total 中
     */
    @PostMapping("/query")
    public ResultJson query(@RequestBody QueryData<College> queryData) {
        Pageable pageable = queryData.buildPageable();
        Page<College> pages = repository.findAll(pageable);
        List<College> courseList = pages.getContent();
        long total = pages.getTotalElements();
        return ResultJson.ok().data("items", courseList).data("total", total);
    }

    /**
     * 查找指定id的学院
     * @param id id
     * @return ResultJson
     */
    @GetMapping("/{id}")
    public ResultJson getById(@PathVariable String id) {
        College college = findById(id);
        return ResultJson.ok().data("item", college);
    }

    @PostMapping("")
    public ResultJson add(@Valid @RequestBody College college) {
        repository.save(college);
        return ResultJson.ok().message("添加" + college + "成功");
    }

    @PutMapping("")
    public ResultJson update(@Valid @RequestBody College college) {
        repository.save(college);
        return ResultJson.ok().message("修改" + college + "成功");
    }

    @DeleteMapping("/{id}")
    public ResultJson deleteById(@PathVariable String id) {
        College college = findById(id);
        repository.delete(college);
        return ResultJson.ok().message("删除" + college + "成功");
    }

    private College findById(String id) {
        return repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "cannot found by id: " + id));
    }
}
